<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/users/', 'Пользователи');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{

		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select('users.*, meta.first_name')->from('users')->join('meta', 'users.id = meta.user_id', 'left')->where_in('group_id', array(1,3))->limit($this->perpage, $from)->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('users')->where_in('group_id', array(1,3))->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/users/index/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/users/index/';
		$config['total_rows'] = $count;
		$config['page_query_string'] = TRUE;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$data['groups'] = $this->ion_auth->get_groups_as_array();

		$this->layout->view('admin/users/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/users/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('users.id', $id)->join('meta', 'users.id = meta.user_id', 'inner')->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/users');

		$page['password'] = "";

		$form = new jQuickForm('simple');

		$form->setLabel(($id == 0?"Добавление":"Редактирование").' пользователя');

//		$gr = $form->insertGroup()->addClass('col col2');

		$form->insertInputText('email')->setLabel('E-mail')->setComment('Используется для входа')->addRuleRequired();
		$pass = $form->insertInputText('password');
		if ($id == 0) {
			$pass->setLabel('Пароль')->setComment('Не менее 8 символов и не более 20');
			$pass->addRuleRequired();
		} else {
			$pass->setLabel('Новый пароль')->setComment('Заполнять только если хотите поменять пароль. Не менее 8 символов и не более 20');
		}

		$groups = $this->ion_auth->get_groups_as_array();
		$select = $form->insertSelect('group_id')->setLabel('Группа');
		foreach ($groups as $group) {
			$select->addOption($group['description'], $group['id']);
		}

		$gr = $form->insertGroup()->addClass('col col2');
		$gr->insertInputText('first_name')->setLabel('Имя')->addRuleRequired();

		$gr = $form->insertGroup()->addClass('col col2');
		/*$gr->insertInputText('company')->setLabel('Компания');
		$gr->insertInputText('phone')->setLabel('Телефон');
		/*
		$gr->insertInputText('address')->setLabel('Юридический адрес')->addRuleRequired();
		$gr->insertInputText('inn')->setLabel('ИНН');
		$gr->insertInputText('kpp')->setLabel('КПП');*/


		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			if ($id == 0) {
				$p_data = $this->input->post();
				$add_data['first_name'] = $p_data['first_name'];
				$add_data['last_name'] = $p_data['last_name'];
				$add_data['company'] = $p_data['company'];
				$add_data['phone'] = $p_data['phone'];

				$result = $this->ion_auth->register(
					$p_data['username'],
					$p_data['password'],
					$p_data['email'],
					$add_data,
					null
					);
				if ($result == false) {
					$this->session->set_flashdata('error', $this->ion_auth->errors());
				} else {
					$this->db->set('group_id', $p_data['group_id'])->where('id', $result)->update('users');
					$this->session->set_flashdata('msg', 'Успешно добавлено');
					redirect('admin/users/edit/'.$result.'/');
				}
			} else {
				$p_data = $this->input->post();
				if ($p_data['password'] == "") unset($p_data['password']);
				$result = $this->ion_auth->update_user($id, $p_data);
				if ($result == true) {
					$this->session->set_flashdata('msg', 'Успешно обновлено');
					redirect('admin/users/edit/'.$id.'/');
				} else {
					$this->session->set_flashdata('error', $this->ion_auth->errors());
				}
			}
		}
		$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/users/edit', $data);
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/users');
		$this->ion_auth->delete_user($id);
		rrmdir("./uploads/user_images/".$id);
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/users/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/users');
		$this->ion_auth->deactivate($id);
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/users/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('users')->where('id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/users');
		$this->ion_auth->activate($id);
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/users/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
}